const validator = require('validator');
const fs = require('fs');
const formidable = require('formidable');
const mineType = require('mime-types');
const Response = require('../common/Response');
const at           = require('../common/at');
const User         = require('../proxy').User;
const Topic        = require('../proxy').Topic;
const TopicCollect = require('../proxy').TopicCollect;
const EventProxy   = require('eventproxy');
const tools        = require('../common/tools');
// const store        = require('../common/store');
const config       = require('../config');
const _            = require('lodash');
// const cache        = require('../common/cache');
const logger = require('../common/logger');

exports.index = function (req, res, next) {
    function isUped(user, reply) {
        if(!reply.ups) {
            return false;
        }
        return reply.ups.indexOf(user._id) !== -1;
    }
    console.log(req.query);
    let query = req.query;
    query.deleted = false;

    let events = ['topic', 'other_topics', 'no_reply_topics', 'is_collect'];
    let ep = EventProxy.create(events,
        function (topic, other_topics, no_reply_topics, is_collect) {
            let result = {
                topic: topic,
                author_other_topics: other_topics,
                no_reply_topics: no_reply_topics,
                is_uped: isUped,
                is_collect: is_collect,
            };
        });

    ep.fail(next);

    Topic.getFullTopic(query, ep.done(function (topic, author, replies) {
        return res.send({code: 1, data: topic});

        topic.visit_count += 1;
        topic.save();

        topic.author = author;
        topic.replies = replies;

        // 点赞数排名第三的回答，它的点赞数就是阈值
        topic.reply_up_threshold = (function () {
            let allUpCount = replies.map(function (reply) {
                return reply.ups && reply.ups.length || 0;
            });

            allUpCount = _.sortBy(allUpCount, Number).reverse();

            let threshold = allUpCount[2] || 0;
            if(threshold < 3) {
                threshold = 3;
            }

            return threshold;
        })();

        ep.emit('topic', topic);

        //get other_topics
        let options = {limit: 5, sort: '-last_reply_at'};
        let query = {
            author_id: topic.author_id,
            _id: {'$nin': [topic._id]}
        };
    }));
};

//所有话题 skip 分页
exports.getFullTopicsBySkit = function (req, res, next) {
    let page = parseInt(req.query.page, 10) || 1;
    let tab_key = req.query.tab_key;

    let query = {deleted: false};
    if(tab_key) {
        query.tab_key = tab_key;
    }
    // var options = { skip: (page - 1) * limit, limit: limit, sort: '-top -last_reply_at'};

    let limit = config.list_topic_count;
    let options = { skip: (page - 1) * limit, limit: limit, sort: '-last_reply_at'};

    Topic.getTopicsByQuery(query, options, function (topics) {
        let response = new Response(1, topics, '');
        res.send(response);
    })
};

//根据用户名查找话题列表
exports.getTopicsByUser = function (req, res, next) {
    // console.log('getTopicsByQuery------',req.query);
    let author_name = req.query.author_name;
    let limit = 5;
    let page = parseInt(req.query.page, 10) || 1;

    if(parseInt(req.query.page, 10)) {
        limit = config.list_topic_count
    }

    let options = {
        skip: (page - 1) * limit,
        limit: limit,
        sort: '-update_at'
    };
    // let query = { author_id: req.query.user_id };

    let query = {
        author_name: author_name,
        deleted: false
    };

    Topic.getTopicsByQuery(query, options, function (topics) {
        // console.log(topics);
        let response = new Response(1, topics, '');
        res.send(response);
    });
};

//热文榜
exports.getTopicsTop = function (req, res, next) {
    // console.log('getTopicsByQuery------',req.query);

    // let query = { author_id: req.query.user_id };

    let query = {
        deleted: false
    };
    let options = {sort: {visit_count: -1}, limit: 5};

    Topic.getTopicsByQuery(query, options, function (topics) {
        let response = new Response(1, topics, '');
        res.send(response);
    });
};

//查看详情
exports.getTopicById = function (req, res, next) {

    let topic_id = req.query.topic_id;

    if(topic_id.length !== 24) {
        let response = new Response(0, '', '此话题不存在或已被删除');
        return res.send(response);
    }

    let query = {_id: topic_id, deleted: false};

    let userLoginId = '';
    if(req.session && req.session.user && req.session.user._id) {
        userLoginId = req.session.user._id;
    }

    Topic.getTopicById(query, function (topic, replies) {
        // console.log(topic);
        if(!topic) {
            let response = new Response(0, '', '没有此话题或已删除');
            res.json(response);
            return;
        }
        topic.visit_count += 1;
        topic.save();

        let collected = '';

        if(userLoginId === '') {
            collected = false;
            let restlt = {
                topic: topic,
                replies: replies,
                collected: collected
            };
            let response = new Response(1, restlt, '');
            res.send(response);
        } else {
            TopicCollect.getTopicCollect(userLoginId, topic_id, function (err, collect) {
                if(err) {
                    next(err);
                }
                collected = collect ? true : false;

                let restlt = {
                    topic: topic,
                    replies: replies,
                    collected: collected
                };
                let response = new Response(1, restlt, '');
                res.send(response);
            });
        }
    });
};


//create topic
exports.put = function (req, res, next) {
    let topic_id = req.body.topic_id || '';
    let title = validator.trim(req.body.title);
    let tab_key = validator.trim(req.body.tab);
    let content = validator.trim(req.body.t_content);
    
    //得到所有的tab， e.g. ['ask', 'share', ...]
    let allTabs = config.tabs.map(function (tPair) {
        return tPair['key'];
    });
    
    //验证
    let editError;
    if(title === '') {
        editError = '标题不能是空的。';
    } else if ( title.length < 5) {
        editError = '标题字数太少, 至少5个字';
    } else if (title.length > 100) {
        editError = '标题字数太多, 最多100个字';
    }else if (!tab_key || allTabs.indexOf(tab_key) === -1) {
        editError = '必须选择一个板块';
    } else if (content === '') {
        editError = '内容不能为空';
    }
    //END 验证
    
    if(editError) {
        let response = new Response(0, '', editError);
        return res.send(response);
    }

    let key_value = '';
    config.tabs.map(function (item) {
        if (item.key === tab_key) {
            key_value = item.value;
        }
    });

    let tab = {
        key: tab_key,
        value: key_value
    };

    // console.log(req.session.user._id);
    let author = {
        authorId: req.session.user._id,
        authorName: req.session.user.name,
        avatar: req.session.user.avatar
    };

    if(topic_id) {
        //重新编辑
        Topic.getTopicById(topic_id, function (topic) {
            if(topic.length === 0) {
                let response = new Response(0, '', '没有此话题或已删除');
                res.json(response);
            }

            if(topic.author_id.toString() === req.session.user._id.toString() || req.session.user.is_admin) {
                topic.content = content;
                topic.update_at = new Date();
                topic.title = title;
                topic.tab_key = tab.key;
                topic.tab_value = tab.value;
                topic.save(function (err) {
                    if (err) {
                        return next(err);
                    }
                    let response = new Response(1, '', '重新编辑成功。');
                    res.json(response);
                });
            } else {
                let response = new Response(0, '', '对不起，你不能编辑此回复。');
                res.json(response);
            }


            // let response = new Response(1, '', '修改成功');
            // res.json(response);
        })
    } else {
        //创建新话题
        Topic.newAndSave(title, content, tab, author, function (err, topic) {
            if (err) {
                return next(err);
            }

            let proxy = new EventProxy();
            proxy.all('score_saved', function () {
                // res.redirect('/topic/' + topic._id);
                let response = new Response(1, '', '发布成功');
                res.send(response);
            });

            proxy.fail(next);

            User.getUserById(req.session.user._id, proxy.done(function (user) {
                user.score += 5;
                user.topic_count += 1;
                user.save();
                req.session.user = user;
                proxy.emit('score_saved');
            }));

            //发送at消息
            // at.sendMessageToMentionUsers(content, topic._id, req.session.user._id);
        });
    }

};

//delete topic
exports.delete = function (req, res, next) {
    let topic_id = req.body.topic_id;

    Topic.getTopicById(topic_id, function (topic) {
        if(!topic) {
            let response = new Response(0, '', '没有此话题或已删除');
            res.json(response);
            return;
        }

        if(topic.author_id.toString() === req.session.user._id.toString() || req.session.user.is_admin) {
            topic.deleted = true;
            topic.save();

            User.getUser({_id: req.session.user._id}, {}, function (err, user) {
                if(err) {
                    return next(err);
                }
                if (!user) {
                    let response = new Response(0, '', '这个用户不存在。');
                    res.send(response);
                    return;
                }
                if(user.topic_count > 0) {
                    user.score -= 5;
                    user.topic_count -= 1;
                }
                user.save();
                req.session.user = user;
            });

            let response = new Response(1, '', '删除成功');
            res.json(response);
        } else {
            let response = new Response(0, '', '嘿嘿，你没有权限哦！');
            res.json(response);
        }
    })
};

/**
 * Topic page
 *
 * @param  {HttpRequest} req
 * @param  {HttpResponse} res
 * @param  {Function} next
 */

exports.topicType = function (req, res, next) {
    let response = new Response(1, config.tabs, '');
    return res.send(response);
};

//收藏话题
exports.collect = function (req, res, next) {
    let topic_id = req.body.topic_id;

    Topic.getTopicById(topic_id, function (topic) {
        // if(err) {
        //     return next(err);
        // }
        if(!topic) {
            let response = new Response(0, '', '没有此主题');
            res.send(response);
        }

        let user_id = req.session.user._id;
        let topic_id = topic._id;

        TopicCollect.getTopicCollect(user_id, topic_id, function (err, doc) {
            if (err) {
                return next(err);
            }
            if (doc) {
                let response = new Response(0, '', '已经收藏该话题');
                res.json(response);
                return;
            }

            TopicCollect.newAndSave(req.session.user._id, topic_id, function (err) {
                if (err) {
                    return next(err);
                }
                let response = new Response(1, '', '收藏成功');
                res.send(response);
            });

            User.getUserById(user_id, function (err, user) {
                if (err) {
                    return next(err);
                }
                user.collect_topic_count += 1;
                user.save();
            });

            req.session.user.collect_topic_count += 1;
            topic.collect_count += 1;
            topic.save();
        })
    });
};

//取消收藏
exports.removeCollect = function (req, res, next) {
    let topic_id = req.body.topic_id;

    Topic.getTopicById(topic_id, function (topic) {
        // console.log('topic--', topic);
        if(!topic) {
            let response = new Response(0, '', '此话题不存在或已被删除');
            return res.json(response);
        }

        let user_id = req.session.user._id;
        TopicCollect.remove(user_id, topic_id, function (err, removeResult) {
            // console.log('topic-----', removeResult);
            if(err) {
                return next(err);
            }
            if (removeResult.n == 0) {
                let response = new Response(0, '', '未关注该话题');
                return res.json(response)
            }

            User.getUserById(user_id, function (err, user) {
                if(err) {
                    return next(err);
                }

                user.collect_topic_count -= 1;
                req.session.user = user;
                user.save();
            });

            topic.collect_count -= 1;
            topic.save();

            let response = new Response(1, '', '取消成功');
            res.json(response)
        })
    });
};

exports.upload = function (req, res, next) {
    let form = new formidable.IncomingForm();
    form.encoding = 'utf-8'; // 编码
    form.keepExtensions = true; // 保留扩展名
    form.maxFieldsSize = 2 * 1024 * 1024; // 文件大小
    // form.uploadDir = 'C:/wpw/keng/keng-node/public/images/';  // 存储路径
    form.parse(req,function(err, fileds, files){ // 解析 formData数据
        if(err){ return console.log('error', err) }

        //多文件上传
        // let urls = {};
        //
        // for(let file in files) {
        //     console.log(files[file], 'legnth------',files.length);
        //     let imgName = files[file].name; // 修改之后的名字
        //     let data = fs.readFileSync(files[file].path); // 同步读取文件
        //     fs.writeFile('../images/content/' + imgName, data, function(err){ // 存储文件
        //         if(err){
        //             let response = new Response(0, '', '上传图片失败');
        //             res.json(response);
        //             return console.log(err);
        //         }
        //         urls[file] = 'http://47.93.192.82/images/content/' + imgName;
        //     })
        // }
        //
        // setTimeout(function () {
        //     let response = new Response(1, urls, '上传成功！');
        //     res.json(response);
        // }, 500)




        //单张图片上传
        let imgName = files.image.name; // 修改之后的名字
        let data = fs.readFileSync(files.image.path); // 同步读取文件

        fs.writeFile('../images/content/' + imgName, data, function(err){ // 存储文件
            if(err){
                let response = new Response(0, '', '上传图片失败');
                res.json(response);
                return console.log(err)
            }

            let url = 'http://47.93.192.82/images/content/' + imgName;

            let response = new Response(1, url, '上传成功！');
            res.json(response);

            // console.log('------------', res);
            // fs.unlink(imgPath,function(){}); // 删除文件
            // res.json({code:1})
            // data = new Buffer(data).toString('base64');
            //
            // let base64 = 'data:' + ';base64,' + data;
            //
            // res.send({code: 1, data:{ url: base64}})
        })
    })

    // let isFileLimit = false;
    // req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
    //     file.on('limit', function () {
    //         isFileLimit = true;
    //
    //         res.json({
    //             success: false,
    //             msg: 'File size too large. Max is ' + config.file_limit
    //         })
    //     });
    //
    //     store.upload(file, {filename: filename}, function (err, result) {
    //         if (err) {
    //             return next(err);
    //         }
    //         if (isFileLimit) {
    //             return;
    //         }
    //         res.json({
    //             success: true,
    //             url: result.url,
    //         });
    //     });
    //
    // });
    //
    // req.pipe(req.busboy);
};